package com.wzj.uarmor.controller;

import cn.hutool.core.lang.UUID;
import com.wzj.uarmor.conf.SystemConfig;
import com.wzj.uarmor.query.LoginQuery;
import com.wzj.uarmor.utils.ResponseStatus;
import com.wzj.uarmor.utils.ResponseVO;
import com.wzj.uarmor.utils.ResultUtil;
import com.wzj.uarmor.utils.TokenUtils;
import com.wzj.uarmor.vo.LoginUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;


/**
 * 登录管理（新）
 *
 * @author whong
 * @date 2023/03/18
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class LoginController {

    private final SystemConfig systemConfig;


    /**
     * 登录
     *
     * @param loginQuery 登录查询
     * @param request    请求
     * @return {@link ResponseVO}
     */
    @PostMapping("/login")
    public ResponseVO login(@RequestBody @Valid LoginQuery loginQuery, HttpServletRequest request){
        if(systemConfig.getUsername().equals(loginQuery.getUsername())&&
            systemConfig.getPassword().equals(loginQuery.getPassword())){
            String token = UUID.randomUUID().toString();
            LoginUser user = new LoginUser();
            user.setUsername(loginQuery.getUsername());
            user.setToken(token);
            HttpSession session = request.getSession();
            session.setAttribute(token,user);
            return ResultUtil.vo(200,"登录成功",user);
        }
        return ResultUtil.error(ResponseStatus.LOGIN_ERROR);
    }


    /**
     * 注销
     *
     * @param request 请求
     * @return {@link ResponseVO}
     */
    @GetMapping("/logout")
    public ResponseVO logout(HttpServletRequest request){
        //清除 session
        String token = TokenUtils.getToken();
        request.getSession().removeAttribute(token);
        return  ResultUtil.vo(200,"登出成功","");
    }
}
